<?php

namespace app\api\model;

use app\member\library\Token;
use app\member\model\Member as Member_Model;
use think\Db;
use think\Exception;
use think\Model;
use util\Random;

class MemberModel extends Model
{
    protected $table = "phome_enewsmember";

    protected $pk = "userid";

    private $keep_time = 86400;

    /**
     * 查找号码
     * @param $mobile
     */
    public function findMemberMobile($mobile){
        $member = $this->where("mobile = {$mobile}")->find();
        return $member;
    }

    /**
     * 查找用户byTOKEN
     * @param $mobile
     */
    public function findMemberByToken($token){
        $member = $this->where("token = '{$token}' ")->find();
        return $member;
    }

    /**
     * 查找专家用户
     */
    public function findProMemberInfo(){

        $proMemberInfo = $this->where(" groupid = 3 ")->select();

        return $proMemberInfo;
    }

    /**
     * 账号密码登录
     * @param $username
     * @param $password
     */
    public function MemberPasswordLogin($username,$password){

        $member = $this->where("username = '{$username}' or mobile = '{$username}' ")->find();
        if($member!=null){
            if($member['password']!=encrypt_password($password, $member->salt)){
                $result = [
                    'msg' => "密码错误",
                    'token' => ""
                ];
            }else{
                $token = Random::uuid();
                //登录计数
                $member['token'] = $token;
                $member['login'] = $member['login']+1;
                $member['last_login_time'] = time();
                $updat=[
                    'token' => $token,
                    'login' => $member['login']+1,
                    'last_login_time' => time()
                ];
                $this->save($updat,"userid = {$member['userid']}");

//                Token::set($token, $member->id, $this->keepTime);
                $memberTokenModel = new MemberTokenModel();
                $memberTokenModel->saveToken($member['userid'],$token);
                $result = [
                    'msg' => "登录成功",
                    'token' => $token
                ];
            }
        }else{
            $result = [
                'token' => "",
                'msg' => "用户不存在"
            ];

        }
        return $result;
    }

    /**
     * 用户登录(手机登录)
     * @param $username
     * @param $password
     */
    public function MemberLogin($member){
        try{
            if($member!=null){
                //保存token
                $token = Random::uuid();
//                $member['token'] = $token;
//                $member['login'] = $member['login']+1;
//                $member['last_login_time'] = time();
                $update = [
                    'token' => $token,
                    'login' => $member['login']+1,
                    'last_login_time' => time()
                ];

                $this->save($update,"userid = {$member['userid']}");

                //保存至member_token
//                Token::set($member['token'], $member->id, $this->keepTime);
                $memberTokenModel = new MemberTokenModel();
                $memberTokenModel->saveToken($member['userid'],$token);
                return true;
            }else{
                return false;
            }
        }catch (Exception $e){
            return false;
        }
    }

    /**
     * 用户注册
     * @param string $mobile
     */
    public function MemberRegister($mobile = ''){
//        $passwordinfo = encrypt_password($password); //对密码进行处理
        $data['mobile'] = $mobile;
//        //新注册用户积分
//        $data['point'] = 0;
//        //新会员注册默认赠送资金
//        $data['amount'] = 0;
//        //新会员注册需要管理员审核
//        $data['status'] = 1;
        //token
        $data['groupid'] = 1;
        $data['token'] = Random::uuid();
        //登录次数
        $data['login'] = 1;
        //最后登录时间
        $data['last_login_time'] = time();
        //密码盐值
        $data['salt'] = genRandomString();
        $params = $data;
//        $params['password'] = $passwordinfo['password'];
        try {
//            $model = new Member_Model();
//            $user = $model->allowField(true)->save($params);
            $this->startTrans();
            $user = $this->save($params);
            if(!$user){
                $this->rollback();
                return 0;
            }else{
                //查询用户
                $member = $this->findMemberMobile($mobile);
                if($member!=null){
                    //保存至member_token
                    $memberTokenModel = new MemberTokenModel();
                    $token['token'] = $data['token'];
                    $token['userid'] = $member['userid'];
                    $token['expiretime'] = time()+$this->keep_time;
                    $token['ceartetime'] = time();
                    $memberTokenModel->insert($token);
                    $this->commit();
                    return $data['token'];
                }else{
                    $this->rollback();
                    return false;
                }
            }
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * 获取会员信息
     * @param $token
     */
    public function getMemberInfo($token){

        $member_token = Db::name("enewsfile_member_token")->where("token = '{$token}' ")->find();
        if($member_token!=null){
            $member = $this->where("userid = {$member_token['userid']}")->find();
            if($member['check']!=1){
                //不显示用户名
                $memberExclude = $this->field(["username","avar"],true)->where("userid = {$member_token['userid']}")->find();

                return $memberExclude;
            }
            return $member;
        }else{
            return false;
        }
    }

    /**
     * 关注用户
     * @param $token
     */
    public function focusMember($token,$focusUid){

       $memberToken = Db::name("enewsfile_member_token")->where("token = '{$token}' ")->find();

       $MemberFocusModel = new MemberFocusModel();
       $flag = $MemberFocusModel->insertfocus($memberToken['userid'],$focusUid);

       if($flag){
           return true;
       }else{
           return false;
       }
    }

    /**
     * 获取关注的用户
     * @param token
     */
    public function getFocusMember($token){

        $memberToken = Db::name("enewsfile_member_token")->where("token = '{$token}' ")->find();
        if($memberToken==null){
            return false;
        }
        $focus = Db::name("enewsfile_member_focus")->where("userid = {$memberToken['userid']}")->select();
        $focusArr = [];
        foreach ($focus as $value){
            $member = $this->where("userid = {$value['userid']}")->find();
            array_push($focusArr,$member);
        }
        return $focusArr;
    }

    /**
     * 保存用户信息
     */
    public function saveMemberInfo($member){
        try {
            $memberInfo = $this->findMemberByToken($member['token']);
            if($memberInfo!=null){
                $this->startTrans();
                    $memberInfo['username'] = empty(trim($member['username']))?$memberInfo['username']:trim($member['username']);
                    $memberInfo['avar'] = empty(trim($member['avar']))?$memberInfo['avar']:trim($member['avar']);
                    $memberInfo->save();
                    $this->save($memberInfo);
                if(!empty($member['labels'])){
                    $memberInterestClazzModel = new MemberInterestClazzModel();
                    $memberInterestClazzModel->insertMemberInterestClazz($memberInfo['userid'],$member['labels']);
                }
                $this->commit();
                return true;
            }else{
                return false;
            }
        }catch (Exception $e){
            $this->rollback();
            return false;
        }
    }

    /**
     * 修改用户密码
     */
    public function modifyPassword($data){
        try{
            $member = $this->findMemberMobile($data['mobile']);
            if($member!=null){
                $this->startTrans();
                $member['password'] = encrypt_password($data['password'],$member->salt);

                $sql = "update phome_enewsmember set password = '{$member['password']}' where mobile = {$data['mobile']}";
                $this->execute($sql);
                return true;
            }else{
                return false;
            }
        }catch (Exception $e){
            $this->rollback();
            return false;
        }
    }

    /**
     * 检查用户名是否重复
     */
    public function checkUsername($data){
        try {
            $count = $this->where("username = '{$data['username']}' ")->count();
            if($count>0){
                return 1;
            }else{
                return -1;
            }
        }catch (Exception $e){
         return 0;
        }
    }


}